﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Frame.Lib.Utilities;
using Frame.Lib.Core.Log;
using Frame.Lib.Core.Cache;
using Frame.Lib.Core.Cache.Paras;
using Frame.Lib.Core.Para;

namespace Frame.Web.Admin.Para
{
    public partial class Edit : PageEdit
    {
        private ParaBO Paras
        {
            get
            {
                return ParaBO.Instance<ParaBO>();
            }
        }
       
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                if (!string.IsNullOrEmpty(this.PKID))
                {
                    DispInfo();
                }
                else
                {
                    txtOrders.Text = Paras.GetMaxOrder().ToString();
                }
            }
        }


        private void DispInfo()
        {
            ParaInfo info = Paras.GetInfo(this.PKID);

            txtID.Text = info.ID;
            txtValue.Text = info.Value;
            txtRemark.Text = info.Remark;
            txtOrders.Text = info.Orders.ToString();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if(string.IsNullOrEmpty(txtID.Text.Trim()))
            {
                Alert("请输入Key");
                return;
            }

            if (Paras.ExistKey(txtID.Text.Trim(), this.PKID))
            {
                Alert("已经存在此key");
                return;
            }

            ParaInfo info = new ParaInfo();
            info.ID = txtID.Text.Trim();
            info.Value = txtValue.Text.Trim();
            info.Remark = txtRemark.Text.Trim();
            try
            {
                info.Orders = int.Parse(txtOrders.Text);
            }
            catch { }

            try
            {
                if (string.IsNullOrEmpty(PKID))
                {
                    this.Paras.Save(info, true);
                    JSUtil.RefreshView(this);
                    this.txtID.Text = txtValue.Text = txtRemark.Text = "";
                    txtOrders.Text = Paras.GetMaxOrder().ToString();

                }
                else
                {
                    this.Paras.Update(info, PKID);
                    JSUtil.RefreshView();
                }

                CacheManager.Instance.GetLoader(typeof(ParasLoader)).Update();
            }

            catch (Exception ex)
            {
                Alert("保存失败");
                Logger.Exception(ex);
            }

            
        }
    }
}